<template>
  <div class="mainWrapper">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="lh lh-diaodu fw_100"></i>
      </el-breadcrumb-item>
      <el-breadcrumb-item>结算管理</el-breadcrumb-item>
      <el-breadcrumb-item>发票管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content_Box box-shadow">
      <div class="py_5 px_10">
        <el-row>
          <el-col :span="2">
            <el-button type="success" @click="downloadOrder" round size="mini"
              >导出</el-button
            >
          </el-col>
          <el-col :span="22">
            <el-form
              :inline="true"
              :model="searchForm"
              class="form-inline fr"
              @keyup.enter.native="searchBtn()"
            >
              <el-form-item>
                <el-input
                  class="w_150"
                  v-model="searchForm.sn"
                  placeholder="发票申请编号"
                  clearable
                ></el-input>
              </el-form-item>
              <lh-agent-list
                @sendValue="setValue"
                :reset="agent_reset"
              ></lh-agent-list>
              <el-form-item>
                <el-select
                  class="w_110"
                  v-model="searchForm.city_id"
                  placeholder="请选择城市"
                  @change="changeCity"
                >
                  <el-option
                    v-for="item in cityList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input
                  class="w_150"
                  v-model="searchForm.company_name"
                  placeholder="公司名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-select
                  class="w_130"
                  v-model="searchForm.shop_sn"
                  filterable
                  placeholder="店铺名称"
                  clearable
                >
                  <el-option
                    v-for="item in shopList"
                    :key="item.shop_sn"
                    :label="item.name"
                    :value="item.shop_sn"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="searchForm.type"
                  placeholder="发票类型"
                  class="w_120"
                  clearable
                >
                  <el-option
                    v-for="item in typeArr"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="searchForm.status"
                  placeholder="状态"
                  class="w_120"
                  clearable
                >
                  <el-option
                    v-for="item in statusArr"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-date-picker
                  size="mini"
                  class="w_180i"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始时间"
                  default-time="00:00:00"
                  v-model="searchForm.start_time"
                ></el-date-picker>
              </el-form-item>
              ~
              <el-form-item>
                <el-date-picker
                  size="mini"
                  class="w_180i"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="结束时间"
                  default-time="23:59:59"
                  v-model="searchForm.end_time"
                ></el-date-picker>
              </el-form-item>
              <el-button
                size="mini"
                type="primary"
                class="round-right"
                native-type="button"
                @click="searchBtn"
                >搜索</el-button
              >
              <el-button size="mini" round @click="resetBtn">重置</el-button>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <!-- 表格数据 -->
      <div class="tableMaxBox">
        <template>
          <el-table :data="tableList" stripe>
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column
              property="sn"
              label="发票申请编号"
              min-width="120"
            ></el-table-column>
            <el-table-column
              property="shop_name"
              label="店铺名称"
            ></el-table-column>
            <el-table-column property="source_detail_num" label="明细">
              <template slot-scope="{ row }">
                <span
                  class="text-primary u cursor-pointer"
                  @click="detailList(row)"
                  >{{ row.source_detail_num }}</span
                >
              </template>
            </el-table-column>
            <el-table-column property="status_name" label="状态"></el-table-column>
            <el-table-column
              property="type_name"
              label="发票类型"
            ></el-table-column>
            <el-table-column
              property="amount"
              label="金额"
            >
              <template slot-scope="{ row }">
                {{ moneyUnitCent2Coin(row.amount) }}
              </template>
            </el-table-column>
            <el-table-column
              property="company_name"
              label="公司名称"
            ></el-table-column>
            <el-table-column
              property="company_tfn"
              label="公司税号"
            ></el-table-column>
            <el-table-column
              property="company_address"
              label="注册地址"
            ></el-table-column>
            <el-table-column
              property="company_phone"
              label="注册电话"
            ></el-table-column>
            <el-table-column
              property="bank_branch_name"
              label="开户银行"
            ></el-table-column>
            <el-table-column
              property="bank_card_id"
              label="银行账号"
            ></el-table-column>
            <el-table-column
              property="apply_remark"
              label="备注"
            ></el-table-column>
            <el-table-column
              property="apply_time_str"
              label="创建时间"
              min-width="150"
            ></el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
              <template slot-scope="{ row }">
                <div style="float: left">
                  <el-link
                    type="warning"
                    :underline="false"
                    class="InfoFont"
                    @click="operation('invoice', row)"
                    v-if="row.status==20"
                    >开票</el-link
                  >
                  <el-link
                    type="info"
                    :underline="false"
                    class="InfoFont"
                    @click="operation('audit', row)"
                    v-if="row.status==10 || row.status==20"
                    >审核</el-link
                  >
                  <el-link
                    type="success"
                    :underline="false"
                    class="InfoFont"
                    @click="operation('update', row)"
                    v-if="row.status==50"
                    >修改</el-link
                  >
                  <el-link
                    type="primary"
                    :underline="false"
                    class="InfoFont"
                    @click="operation('details', row)"
                    >查看详情</el-link
                  >
                  <el-link
                    type="danger"
                    :underline="false"
                    class="InfoFont"
                    @click="operation('invalid', row)"
                    v-if="row.status==50"
                    >作废</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 开票-弹框 -->
          <el-dialog
            :title="dialogTitle"
            :visible.sync="invoiceDialog"
            width="560px"
            :close-on-click-modal="false"
            :before-close="hiddenDialog"
          >
            <div class="auditCentent">
              <div class="row-info clear mb_20">
                <div class="fl title-key">
                  公司名称：
                </div>
                <div class="fl list-cont">
                  {{ selectItem.company_name }}
                </div>
              </div>
              <div class="row-info clear mb_20">
                <div class="fl title-key">
                  金额：
                </div>
                <div class="fl list-cont">
                   {{ moneyUnitCent2Coin(selectItem.amount) }}
                </div>
              </div>
              <div class="row-info clear mb_20">
                <div class="fl title-key">
                  <i class="lhadmin lhadmin-wujiaoxing"></i>发票编号：
                </div>
                <div class="fl list-cont">
                  <el-input v-model="invoiceMsg.invoice_code" maxlength='8'></el-input>
                </div>
              </div>
              <div class="row-info clear mb_20">
                <div class="fl title-key">快递公司：</div>
                <div class="fl list-cont">
                  <el-select
                    v-model="invoiceMsg.express_company_sn"
                    @change="changeExpress"
                  >
                    <el-option
                      v-for="item in courierArr"
                      :key="item.sn"
                      :label="item.name"
                      :value="item.sn"
                    ></el-option>
                  </el-select>
                </div>
              </div>
              <div class="row-info clear mb_20" v-if="invoiceMsg.express_company_sn != 0">
                <div class="fl title-key">
                  <i class="lhadmin lhadmin-wujiaoxing"></i>快递单号：
                </div>
                <div class="fl list-cont">
                  <el-input v-model="invoiceMsg.express_code"></el-input>
                </div>
              </div>
              <div class="row-info clear">
                <div class="fl title-key">备注：</div>
                <div class="fl list-cont">
                  <el-input
                    type="textarea"
                    :rows="4"
                    :cols="32"
                    v-model="invoiceMsg.remark"
                    maxlength="255"
                    show-word-limit
                  ></el-input>
                </div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer">
              <span class="btnOK mr_20" @click="confirmInvoice()">确 定</span>
              <span class="resetBtn" @click="hiddenDialog">取 消</span>
            </div>
          </el-dialog>

          <!-- 发票审核-弹框 -->
          <el-dialog
            :title="dialogTitle"
            :visible.sync="auditDialog"
            width="560px"
            :close-on-click-modal="false"
            :before-close="hiddenDialog"
          >
            <div class="auditCentent">
              <div class="row-info clear mb_20">
                <div class="fl title-key">
                  <i class="lhadmin lhadmin-wujiaoxing"></i>审核：
                </div>
                <div class="fl list-cont">
                  <el-radio v-if="selectItem.status != '20'" v-model="auditTag" label="20">审核通过</el-radio>
                  <el-radio v-model="auditTag" label="40">驳回</el-radio>
                </div>
              </div>
              <div class="row-info clear" v-if="auditTag == 40">
                <div class="fl title-key">
                  <i class="lhadmin lhadmin-wujiaoxing"></i>驳回原因：
                </div>
                <div class="fl list-cont">
                  <el-input
                    type="textarea"
                    :rows="4"
                    :cols="32"
                    v-model="remark"
                    maxlength="255"
                    show-word-limit
                  ></el-input>
                </div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer">
              <span class="btnOK mr_20" @click="confirmAudit()">确 定</span>
              <span class="resetBtn" @click="hiddenDialog">取 消</span>
            </div>
          </el-dialog>

          <!-- 发票作废-弹框 -->
          <el-dialog
            :title="dialogTitle"
            :visible.sync="invalidDialog"
            width="560px"
            :close-on-click-modal="false"
            :before-close="hiddenDialog"
          >
            <div class="auditCentent">
              <div class="row-info clear">
                <div class="fl title-key">
                  <i class="lhadmin lhadmin-wujiaoxing"></i>作废原因：
                </div>
                <div class="fl list-cont">
                  <el-input
                    type="textarea"
                    :rows="4"
                    :cols="32"
                    v-model="remark"
                    maxlength="255"
                    show-word-limit
                  ></el-input>
                </div>
              </div>
              <div class="row-info clear mt_20">
                <div class="fl list-cont ml_80">
                  <p class="danger">确认要将该条记录作废吗？</p>
                  <p class="danger">作废后对应任务/结算单将恢复为未开票状态</p>
                </div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer">
              <span class="btnOK mr_20" @click="confirmInvalid()"
                >确 定 作 废</span
              >
              <span class="resetBtn" @click="hiddenDialog">取 消</span>
            </div>
          </el-dialog>

          <!-- 分页组件 -->
          <page
            :total="total"
            :pageNums="pageNum"
            :disableMountedFetch="true"
            @pagedata="onChildValue"
          ></page>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import { 
  fetchInvoiceEnum,
  fetchInvoiceList,
  invoiceAudit,
  invoiceMake,
  invoiceLnvalid,
  invoiceEdit,
  fetchExpressList
} from "@/api/invoice.js"
import { fetchShopList } from "@/api/shop.js"
import qs from "qs"
const common = require("../../../static/tool.js")
export default {
  name: "invoiceList",
  data() {
    return {
      url: common.url,
      searchForm: {
        sn: "", //发票编号
        city_id: "", //城市
        company_name: "", //公司
        shop_sn: "", //店铺
        type: "", //发票类型
        status: 10, //状态
        start_time: "", //开始时间
        end_time: "", //结束时间
      },
      agent_id: "", //代理商
      tableList: [], //列表数据
      shopList: [], // 店铺列表
      cityList: [], //城市列表
      typeArr: [], //发票类型
      statusArr: [], //状态
      pageNum: 1,
      pageSizeNow: 20,
      total: 0,
      selectItem: {}, //选中数据
      selectType: '', //编辑类型
      dialogTitle: "", //弹窗title
      auditDialog: false, //审核弹窗
      auditTag: "20", //审核标签
      remark: "", //备注
      invoiceDialog: false, //开票弹窗
      invoiceMsg:{
        invoice_code: '', //发票编号
        express_company_sn: '', //快递公司编号
        express_code: '', //快递单号
        remark: '', //备注
      },
      courierArr: [],//快递公司
      invalidDialog: false, //作废弹窗
      agent_reset: 0, //重置代理商
    }
  },
  watch: {
    'invoiceMsg.invoice_code': {
      handler(val) {
        this.invoiceMsg.invoice_code = val.replace(/[^\d]/g, '') 
      },
      deep: true
    }
  },
  mounted() {
    this.defaultTime()
    this.fetchInvoiceEnum()
  },
  methods: {
    //搜索默认时间
		defaultTime(){
			let start = this.date(-7)
			this.searchForm.start_time = start + ' 00:00:00'
			let end = this.date()
			this.searchForm.end_time = end + ' 23:59:59'
		},
    //时间处理器
		date(e) {
			return this.$moment().add('days', e).format('YYYY-MM-DD')
		},
    //枚举选项
    async fetchInvoiceEnum(){
      try {
        let res = await fetchInvoiceEnum({
          type: "type,status"
        })
        this.typeArr = res.type
        this.statusArr = res.status
      } catch (error) {
        console.log("获取枚举项：" + error)
      }
    },
    //导出
    downloadOrder() {
      const params = qs.stringify({
        token: JSON.parse(sessionStorage.getItem("manageInfo")).token,
        ...this.searchForm
      })

      window.location.href =
        this.url + "/invoice/exportList?" + params
    },
    //搜索
    searchBtn() {
      this.getList()
    },
    //重置
    resetBtn() {
      Object.keys(this.searchForm).forEach(
        (key) => (this.searchForm[key] = "")
      )
      // 重置代理商
      this.agent_reset += 1
      this.areaStatus = true
      this.defaultTime()
      this.searchForm.status = 10
    },
    //查看明细
    detailList(item) {
      if(item.source == 1){
        this.$router.push({
          path: "/invoice-task-list",
          query: {
            sn: item.sn,
            source: item.source
          }
        })
      }else if(item.source == 2){
        this.$router.push({
          path: "/invoice-statement-list",
          query: {
            sn: item.sn,
            source: item.source
          }
        })
      }
    },
    //操作-弹窗
    operation(type, item) {
      console.log(item);
      this.selectItem = item
      this.selectType = type
      switch (type) {
        case "invoice":
          this.fetchExpressList()
          this.invoiceDialog = true
          this.dialogTitle = "开票"
          break
        case "audit":
          this.auditDialog = true
          this.dialogTitle = "开票审核"
          if(item.status == 20){
            this.auditTag = '40'
          }
          break
        case "update":
          this.fetchExpressList()
          this.invoiceDialog = true
          this.dialogTitle = "修改"
          this.invoiceMsg.express_company_sn = item.express_company_sn
          this.invoiceMsg.express_code = item.express_code
          this.invoiceMsg.invoice_code = item.invoice_code
          this.invoiceMsg.remark = item.make_remark
          break
        case "details":
          this.$router.push({
            path: "/invoice-details",
            query: {
              sn: item.sn
            }
          })
          break
        case "invalid":
          this.invalidDialog = true
          this.dialogTitle = "开票作废"
          break
        default:
          break
      }
    },
    //确定开票
    async confirmInvoice() {
      if(this.invoiceMsg.invoice_code == ''){
        this.$message.error('请填写发票编号') 
        return
      }
      if(this.invoiceMsg.express_company_sn != '' && this.invoiceMsg.express_code == ''){
        this.$message.error('请填写快递单号') 
        return
      }else if(this.invoiceMsg.express_company_sn == ''){
        this.invoiceMsg.express_code = ''
      }
      try {
        if(this.selectType == 'invoice'){ //开票
          await invoiceMake({
            sn: this.selectItem.sn,
            ...this.invoiceMsg
          })
        }else if(this.selectType == 'update'){ //修改
          await invoiceEdit({
            sn: this.selectItem.sn,
            ...this.invoiceMsg
          })
        }
        this.hiddenDialog()
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      } catch (error) {
        console.log("确定审核：" + error)
      }
    },
    //获取快递公司
    async fetchExpressList(){
      try {
        let res = await fetchExpressList()
        res.unshift({ sn: '', name: '不邮寄' })
        this.courierArr = res
      } catch (error) {
        console.log("获取快递公司：" + error)
      }
    },
    //改变快递公司
    changeExpress(e){
      console.log(e);
    },
    //确定审核
    async confirmAudit() {
      if(this.auditTag == '40' && this.remark == ''){ 
        this.$message.error('请填写驳回原因') 
        return
      }
      try {
        await invoiceAudit({
          sn: this.selectItem.sn,
          status: this.auditTag,
          remark: this.remark
        })
        this.hiddenDialog()
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      } catch (error) {
        console.log("确定审核：" + error)
      }
    },
    //确定作废
    async confirmInvalid() {
      if(this.remark == ''){ 
        this.$message.error('请填写作废原因') 
        return
      }
      try {
        await invoiceLnvalid({
          sn: this.selectItem.sn,
          remark: this.remark
        })
        this.hiddenDialog()
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      } catch (error) {
        console.log("确定审核：" + error)
      }
    },
    //隐藏弹窗
    hiddenDialog() {
      this.invoiceDialog = false
      this.auditDialog = false
      this.invalidDialog = false
      this.selectItem = ''
      this.remark = ''
      this.invoiceMsg.invoice_code = ''
      this.invoiceMsg.express_company_sn = ''
      this.invoiceMsg.express_code = ''
      this.invoiceMsg.remark = ''
      this.getList()
    },
    //列表数据
    async getList() {
      try {
        let res = await fetchInvoiceList({
          page: this.pageNum,
          page_size: this.pageSizeNow,
          agent_id: this.agent_id,
          ...this.searchForm,
        })
        this.tableList = res.list
        this.total = res.total
      } catch (err) {
        console.log("获取发票列表："+err)
      }
    },
    //代理商
    async setValue(data) {
      this.searchForm.shop_name = ""
      this.agent_id = data.agent_id
      this.cityList = data.city_list
      this.searchForm.city_id = +this.cityList[0].id
      this.getList()
      this.fetchShopList() //店铺列表
    },
    // 监听城市val变化
    changeCity() {
      this.searchForm.shop_name = ""
      this.fetchShopList() //店铺列表
    },
    //店铺列表
    async fetchShopList() {
      try {
        let ret = await fetchShopList({
          sign_status: 30, //已合作的店铺
          status: 1, //启用的店铺
          city_id: this.searchForm.city_id,
          agent_id: this.agent_id,
        })
        if (ret.list.length) {
          ret.list.forEach((item) => {
            item.value = item.name
          })
          this.shopList = ret.list
        } else {
          this.shopList = []
        }
      } catch (err) {
        console.log(err)
      }
    },

    //分页组件->子组件传值
    onChildValue(item) {
      this.pageNum = item[0]
      this.pageSizeNow = item[1]
      this.getList()
    },
  },
}
</script>
<style scoped lang="scss">
.success {
  color: green !important
}
.danger {
  color: red !important;
  font-weight: bold
}
</style>


// WEBPACK FOOTER //
// src/components/invoice/List.vue